<template>
  <el-drawer
    v-model="visible"
    title="性能监控"
    direction="rtl"
    size="400px"
    :before-close="handleClose"
  >
    <div class="performance-monitor">
      <!-- 总览 -->
      <el-card class="monitor-section">
        <template #header>
          <div class="section-header">
            <span>性能总览</span>
            <el-button-group size="small">
              <el-button 
                :type="isMonitoring ? 'danger' : 'primary'"
                @click="toggleMonitoring"
              >
                {{ isMonitoring ? '停止监控' : '开始监控' }}
              </el-button>
              <el-button @click="clearMetrics">清空数据</el-button>
            </el-button-group>
          </div>
        </template>
        
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-label">测量次数</div>
            <div class="stat-value">{{ stats?.count || 0 }}</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">总耗时</div>
            <div class="stat-value">{{ stats?.total || 0 }}ms</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">平均耗时</div>
            <div class="stat-value">{{ stats?.average || 0 }}ms</div>
          </div>
          <div class="stat-item">
            <div class="stat-label">最大耗时</div>
            <div class="stat-value">{{ stats?.max || 0 }}ms</div>
          </div>
        </div>
      </el-card>

      <!-- 内存使用 -->
      <el-card class="monitor-section" v-if="memoryInfo">
        <template #header>
          <span>内存使用情况</span>
        </template>
        
        <div class="memory-info">
          <div class="memory-item">
            <span class="memory-label">已使用:</span>
            <span class="memory-value">{{ formatMemorySize(memoryInfo.usedJSHeapSize) }}</span>
          </div>
          <div class="memory-item">
            <span class="memory-label">总分配:</span>
            <span class="memory-value">{{ formatMemorySize(memoryInfo.totalJSHeapSize) }}</span>
          </div>
          <div class="memory-item">
            <span class="memory-label">限制:</span>
            <span class="memory-value">{{ formatMemorySize(memoryInfo.jsHeapSizeLimit) }}</span>
          </div>
          
          <el-progress
            :percentage="memoryUsagePercentage"
            :color="getMemoryColor(memoryUsagePercentage)"
            :show-text="false"
            style="margin-top: 12px;"
          />
          <div class="memory-percentage">
            内存使用率: {{ memoryUsagePercentage.toFixed(1) }}%
          </div>
        </div>
      </el-card>

      <!-- 最近测量 -->
      <el-card class="monitor-section">
        <template #header>
          <span>最近测量 ({{ recentMetrics.length }})</span>
        </template>
        
        <div class="recent-metrics">
          <div
            v-for="metric in recentMetrics"
            :key="`${metric.name}-${Date.now()}`"
            class="metric-item"
          >
            <div class="metric-name">{{ metric.name }}</div>
            <div class="metric-duration" :class="getDurationClass(metric.duration)">
              {{ metric.duration }}ms
            </div>
          </div>
          
          <div v-if="recentMetrics.length === 0" class="empty-metrics">
            暂无测量数据
          </div>
        </div>
      </el-card>

      <!-- 缓存统计 -->
      <el-card class="monitor-section">
        <template #header>
          <div class="section-header">
            <span>缓存统计</span>
            <el-button size="small" @click="refreshCacheStats">刷新</el-button>
          </div>
        </template>
        
        <div class="cache-stats">
          <div class="cache-item">
            <span class="cache-label">搜索缓存:</span>
            <span class="cache-value">{{ searchCacheStats.size }}/{{ searchCacheStats.maxSize }}</span>
          </div>
          <div class="cache-item">
            <span class="cache-label">使用率:</span>
            <span class="cache-value">{{ searchCacheStats.usage.toFixed(1) }}%</span>
          </div>
          
          <el-progress
            :percentage="searchCacheStats.usage"
            :color="getCacheColor(searchCacheStats.usage)"
            :show-text="false"
            style="margin-top: 8px;"
          />
        </div>
      </el-card>

      <!-- 页面加载性能 -->
      <el-card class="monitor-section" v-if="pageLoadMetrics">
        <template #header>
          <span>页面加载性能</span>
        </template>
        
        <div class="page-metrics">
          <div class="page-metric">
            <span class="metric-label">DNS查询:</span>
            <span class="metric-value">{{ pageLoadMetrics.dnsLookup }}ms</span>
          </div>
          <div class="page-metric">
            <span class="metric-label">TCP连接:</span>
            <span class="metric-value">{{ pageLoadMetrics.tcpConnect }}ms</span>
          </div>
          <div class="page-metric">
            <span class="metric-label">请求响应:</span>
            <span class="metric-value">{{ pageLoadMetrics.request }}ms</span>
          </div>
          <div class="page-metric">
            <span class="metric-label">DOM解析:</span>
            <span class="metric-value">{{ pageLoadMetrics.domParse }}ms</span>
          </div>
          <div class="page-metric">
            <span class="metric-label">页面加载:</span>
            <span class="metric-value">{{ pageLoadMetrics.pageLoad }}ms</span>
          </div>
        </div>
      </el-card>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { usePerformance } from '../composables/usePerformance'
import { useSearchStore } from '../stores/search'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const searchStore = useSearchStore()

const {
  stats,
  memoryInfo,
  isMonitoring,
  formatMemorySize,
  getRecentMetrics,
  clearMetrics,
  startMonitoring,
  stopMonitoring,
  updateMemoryInfo,
  getPageLoadMetrics
} = usePerformance()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const recentMetrics = computed(() => getRecentMetrics(10))
const pageLoadMetrics = computed(() => getPageLoadMetrics())
const searchCacheStats = ref(searchStore.getSearchCacheStats())

// 内存使用率
const memoryUsagePercentage = computed(() => {
  if (!memoryInfo.value) return 0
  return (memoryInfo.value.usedJSHeapSize / memoryInfo.value.jsHeapSizeLimit) * 100
})

// 获取内存颜色
const getMemoryColor = (percentage: number) => {
  if (percentage > 80) return '#f56c6c'
  if (percentage > 60) return '#e6a23c'
  return '#67c23a'
}

// 获取缓存颜色
const getCacheColor = (percentage: number) => {
  if (percentage > 90) return '#f56c6c'
  if (percentage > 70) return '#e6a23c'
  return '#409eff'
}

// 获取持续时间样式类
const getDurationClass = (duration: number) => {
  if (duration > 1000) return 'duration-slow'
  if (duration > 500) return 'duration-medium'
  return 'duration-fast'
}

// 切换监控状态
const toggleMonitoring = () => {
  if (isMonitoring.value) {
    stopMonitoring()
  } else {
    startMonitoring()
  }
}

// 刷新缓存统计
const refreshCacheStats = () => {
  Object.assign(searchCacheStats.value, searchStore.getSearchCacheStats())
  updateMemoryInfo()
}

// 处理关闭
const handleClose = () => {
  visible.value = false
}

// 定时更新内存信息
let memoryUpdateTimer: NodeJS.Timeout | null = null

onMounted(() => {
  updateMemoryInfo()
  refreshCacheStats()
  
  // 每5秒更新一次内存信息
  memoryUpdateTimer = setInterval(() => {
    if (visible.value) {
      updateMemoryInfo()
      refreshCacheStats()
    }
  }, 5000)
})

onUnmounted(() => {
  if (memoryUpdateTimer) {
    clearInterval(memoryUpdateTimer)
  }
})
</script>

<style scoped>
.performance-monitor {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.monitor-section {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 12px;
  background-color: var(--el-color-info-light-9);
  border-radius: 6px;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-bottom: 4px;
}

.stat-value {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-color-primary);
}

.memory-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.memory-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
}

.memory-label {
  color: var(--el-text-color-regular);
}

.memory-value {
  font-weight: 600;
  color: var(--el-text-color-primary);
  font-family: monospace;
}

.memory-percentage {
  text-align: center;
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-top: 4px;
}

.recent-metrics {
  max-height: 200px;
  overflow-y: auto;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.metric-item:last-child {
  border-bottom: none;
}

.metric-name {
  font-size: 13px;
  color: var(--el-text-color-primary);
}

.metric-duration {
  font-size: 12px;
  font-weight: 600;
  font-family: monospace;
}

.duration-fast {
  color: var(--el-color-success);
}

.duration-medium {
  color: var(--el-color-warning);
}

.duration-slow {
  color: var(--el-color-danger);
}

.empty-metrics {
  text-align: center;
  color: var(--el-text-color-placeholder);
  font-size: 13px;
  padding: 20px;
}

.cache-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.cache-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 13px;
}

.cache-label {
  color: var(--el-text-color-regular);
}

.cache-value {
  font-weight: 600;
  color: var(--el-text-color-primary);
  font-family: monospace;
}

.page-metrics {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.page-metric {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.metric-label {
  color: var(--el-text-color-regular);
}

.metric-value {
  font-weight: 600;
  color: var(--el-text-color-primary);
  font-family: monospace;
}
</style>